﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Web.Mvc;
using NHibernate;
using Mailer.Model;
using Mailer.Model.Types;
using NHibernate.Criterion;

namespace Mailer.Controllers
{
	[HandleError]
	public class PublicAppController : Controller
	{
		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Subscribe(Guid id)
		{
			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				var app = sess.Get<Application>(id);
				if (app != null)
				{
					Utilities.ApplyCustomStyling(ViewData, app);
					
					ViewData["lists"] = sess.CreateCriteria<List>().Add(Expression.Eq("IsPublic", true)).Add(Expression.Eq("ApplicationID", app.ID)).List<List>();
				}

				SessionUtilities.EndSession(sess);
			}
			return base.View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Subscribe(Guid id, string name, string email, Guid[] lists)
		{
			ActionResult res = null;

			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				var app = sess.Get<Application>(id);
				if (app != null)
				{
					Utilities.ApplyCustomStyling(ViewData, app);
					using (ITransaction transaction = sess.BeginTransaction())
					{ 
						var recip = sess.CreateCriteria<Recipient>().Add(Expression.Eq("Email", email)).Add(Expression.Eq("ApplicationID", app.ID)).UniqueResult<Recipient>();
						if (recip != null)
						{
							recip.UpdatedBy = Guid.Empty;
							recip.UpdatedDate = DateTime.Now;
							recip.State = (int)RecipientState.Verified;

							if (lists != null)
							{
								foreach (Guid list in lists)
								{
									var listobj = sess.Get<List>(list);
									if (!recip.Lists.Contains(listobj))
										recip.Lists.Add(listobj);
								}
							}

							sess.Save(recip);

							if (!string.IsNullOrEmpty(name))
								recip.SetPropertyValue(sess, "displayname", name);
						}
						else
						{
							var newrecip = new Recipient();
							newrecip.ApplicationID = app.ID;

							if (lists != null)
							{
								foreach (Guid list in lists)
								{
									List listobj = sess.Get<List>(list);
									if (!newrecip.Lists.Contains(listobj))
										newrecip.Lists.Add(listobj);
								}
							}

							newrecip.Email = email;
							newrecip.CreatedBy = Guid.Empty;
							newrecip.CreatedDate = DateTime.Now;
							newrecip.UpdatedBy = Guid.Empty;
							newrecip.UpdatedDate = DateTime.Now;
							newrecip.State = (int)RecipientState.Verified;
							sess.Save(newrecip);

							if (!string.IsNullOrEmpty(name))
								newrecip.SetPropertyValue(sess, "displayname", name);
						}

						// TODO: skicka infomail

						ViewData["email"] = "";
						ViewData["name"] = "";

						// ModelState.Add(  .AddModelError("_FORM", ErrorCodeToString(createStatus));

						res = RedirectToAction("SubscribeThanks", new { id = id });

						transaction.Commit();
					}
				}
				SessionUtilities.EndSession(sess);
			}

			return RedirectToAction("SubscribeThanks");
		}


		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult SubscribeThanks(Guid id)
		{
			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				var app = sess.Get<Application>(id);
				if (app != null)
				{
					Utilities.ApplyCustomStyling(ViewData, app);
				}
				SessionUtilities.EndSession(sess);
			}
			return base.View();
		}









		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult Unsubscribe(Guid id)
		{
			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				var app = sess.Get<Application>(id);
				if (app != null)
				{
					Utilities.ApplyCustomStyling(ViewData, app);
					ViewData["lists"] = sess.CreateCriteria<List>().Add(Expression.Eq("IsPublic", true)).Add(Expression.Eq("ApplicationID", app.ID)).List<List>();
				}
				SessionUtilities.EndSession(sess);
			}

			return View();
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Unsubscribe(Guid id, string email, Guid[] lists)
		{ 
			var sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				var app = sess.Get<Application>(id);
				if (app != null)
				{
					Utilities.ApplyCustomStyling(ViewData, app);

					using (var transaction = sess.BeginTransaction())
					{
						IList<Recipient> recips = sess.CreateCriteria<Recipient>()
							.Add(Expression.Eq("Email", email))
							.Add(Expression.Eq("ApplicationID", app.ID))
							.List<Recipient>();

						foreach (var recip in recips)
						{
					//	}
					//	if (recip != null)
					//	{
							recip.UpdatedBy = Guid.Empty;
							recip.UpdatedDate = DateTime.Now;
							foreach (Guid g in lists)
							{
								List list = sess.Get<List>(g);
								if (list != null)
									if (recip.Lists.Contains(list))
										recip.Lists.Remove(list);
							}
							sess.Save(recip);
						}

						transaction.Commit();
					}
				}
				SessionUtilities.EndSession(sess);
			}

			return RedirectToAction("UnsubscribeThanks");
		}


		[AcceptVerbs(HttpVerbs.Get)]
		public ActionResult UnsubscribeThanks(Guid id)
		{
			ISession sess = SessionUtilities.BeginSession();
			if (sess != null)
			{
				Application app = sess.Get<Application>(id);
				if (app != null)
				{
					Utilities.ApplyCustomStyling(ViewData, app);
				}
				SessionUtilities.EndSession(sess);
			}
			return base.View();
		}


	}
}
